package nl.windgazer.arachne.mixins;

import java.util.Locale;

import org.apache.tapestry5.Asset;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.annotations.AfterRender;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.services.SymbolSource;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.AssetSource;
import org.apache.tapestry5.services.javascript.InitializationPriority;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;

import com.google.code.zeroclipboard.ZeroclipboardConstants;

@Import( library = "ZeroclipboardMixin.js" )
public class ZeroclipboardMixin {

	private static final String ZEROCLIPBOARD_STRING = "ZeroclipboardString";
	private static final String ZEROCLIPBOARD_DOM = "ZeroclipboardDOM";

	//Injects and Persists

	@Inject
	private SymbolSource _symbols;

	@Inject
	private JavaScriptSupport _jss;

	@Inject
	private AssetSource _as;

	@Inject
	private Locale _locale;

	@Inject
	private Messages _msgs;

	//Properties and Parameters

	@Parameter
	private String _target;

	@Parameter
	private String _origin;

	@Parameter
	private String _clipping;

	@Parameter
	private boolean _hand = true;

	//Components

	//Events

	@AfterRender
	void setupScripsAndSuch(MarkupWriter writer) {
		final String target = _target!=null?_target:writer.getElement().getAttribute("id"); 
		final Asset flash = _as.getAsset(null, ZeroclipboardConstants.getAssetDir(_symbols, "ZeroClipboard.swf"), _locale);
		final Asset js = _as.getAsset(null, ZeroclipboardConstants.getAssetDir(_symbols, "ZeroClipboard.js"), _locale);
		_jss.importJavaScriptLibrary(js);
		final JSONObject config = new JSONObject(
				"value", _clipping
				, "movie", flash.toClientURL()
				, "hand", Boolean.toString(_hand)
				, "target", target
				, "alert", _msgs.get("zeroclipboard.alert")
				, "origin", _origin
		);
		_jss.addInitializerCall(InitializationPriority.LATE, _origin==null?ZEROCLIPBOARD_STRING:ZEROCLIPBOARD_DOM, config);
//		_jss.addInitializerCall(_origin==null?ZEROCLIPBOARD_STRING:ZEROCLIPBOARD_DOM, config);
	}

	//Other (check for business-logic, it should not remain here)

}
